package com.yociyy.gate.filter;

import com.yociyy.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * 网关全局过滤器 作用：鉴权
 * 
 * @author: YoCiyy
 * @date: 2020/4/27
 */
@Component
@Slf4j
@Order(0)
public class GatewayGlobalFilter implements GlobalFilter {

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 网关过滤器放行白名单
	 */
	private static final String[] whiteList = {
			"/auth/login",
			"/auth/user/token",
			"/v2/api-docs",
			"/auth/v2/api-docs"
	};

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		String url = exchange.getRequest().getURI().getPath();

		// 放行白名单请求路由
		if (Arrays.asList(whiteList).contains(url)) {
			return chain.filter(exchange);
		}

//		// 请求头中获取token信息
//		String token = exchange.getRequest().getHeaders().getFirst("Access-Token");
//		if (StrUtil.isBlank(token)) {
//			log.info("token can't null or empty string");
//			exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
//			return exchange.getResponse().setComplete();
//		}
//
//		// 校验用户信息
//		 String userJsonStr = redisUtils.get(Constants.ACCESS_TOKEN + token);
//
//		if (StrUtil.isBlank(userJsonStr)) {
//			log.info("user token forbidden or expired!");
//			exchange.getResponse().setStatusCode(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
//			return exchange.getResponse().setComplete();
//		}
//		JSONObject json = JSONObject.parseObject(userJsonStr);
//		String userId = json.getString("id");
//		String account = json.getString("account");
//		if (StrUtil.isBlank(userId)) {
//			log.info("user verify error or user doesn't exist");
//			exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
//			return exchange.getResponse().setComplete();
//		}

		// 设置userId到request里，后续根据userId，获取用户信息
		ServerHttpRequest req = exchange.getRequest().mutate()
//				.header(Constants.CURRENT_ID, userId)
//				.header(Constants.CURRENT_USERNAME, account)
				.build();
		// 放行
//		return chain.filter(exchange.mutate().request(req).build());
		return chain.filter(exchange);


	}
}
